<?php
/*
 +----------------------------------------------------------------------
 + Title        : TokenService 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2021/6/10 14:11
 + Last-time    : 2021/6/10 14:11+ chen2
 + Desc         : TokenService
 +----------------------------------------------------------------------
*/


namespace app\common\service;


use Firebase\JWT\JWT;

use Firebase\JWT\Key;

use function config;
use function error_abort;

class TokenService extends BaseService {
    /**
     * 产生Token
     *
     * @access public
     *
     * @param int    $id       编号
     * @param int    $type     1=管理组
     * @param string $username 账号
     * @param string $platform 来源平台
     *
     * @return false|array
     */
    public static function setToken($id, $type, $username, $platform)
    {
        $key = config('app.token_key');
        $iat = time();
        $nbf = $iat;
        $payload = [
            "iss"  => $_SERVER['SERVER_NAME'], //发行人
            "aud"  => 'www.test',//$_SERVER['HTTP_ORIGIN'], //用户
            "exp"  => $iat +3600*24,
            "iat"  => $iat, //发布时间
            "nbf"  => $nbf, //在此之前不可用
            "data" => [
                "user_id" => $id,
                "type"=>$type,
                "username"=>$username,
                "platform"=>$platform,
            ]
        ];
        $jwt = JWT::encode($payload, $key ,'HS256');
        return $jwt;
    }


    public static function checkToken($token) {
        $key = config('app.token_key');
//        JWT::$leeway = 60;

        try {
            $decoded = JWT::decode($token, new Key($key, 'HS256'));//
//            error_abort('登录已过期', '403');
            if($decoded->exp < time()){
                error_abort('登录已过期', '403');
            }
            return (array)$decoded->data;
        } catch (\Exception $e) {
            error_abort('token验证失败', 401);
        }
    }
}
